package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.Utils.DateUtils;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/*报表操作*/
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;


    //会员数量
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();//获的日历对象,模拟时间就是当前时间
        Date time = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
        String format = sdf.format(time);
        System.out.println(format);
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH, -12);//获取当前时间往前倒推12个月的时间
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//获得当前时间往后推一个月的日期
            Date time1 = calendar.getTime();
            String date = sdf.format(time1);
            months.add(date);
        }
        map.put("months", months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //套餐预约占比
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //使用模拟数据测试使用什么样的java对象转为饼图所需的json格式
       /* Map<String, Object> map = new HashMap<>();
        List<String> setmealNames = new ArrayList<>();
        setmealNames.add("体检套餐");
        setmealNames.add("孕前检查套餐");
        map.put("setmealNames", setmealNames);
        List<Map<String, Object>> setmealCount = new ArrayList<>();
        Map<String, Object> m1 = new HashMap<>();
        m1.put("name", "体检套餐");
        m1.put("value", "200");
        Map<String, Object> m2 = new HashMap<>();
        m2.put("name", "孕前检查套餐");
        m2.put("value", "500");
        setmealCount.add(m1);
        setmealCount.add(m2);
        map.put("setmealCount", setmealCount);*/
        //后台代码来查询真实数据
        Map<String, Object> map = new HashMap<>();
        List<String> setmealNames = new ArrayList<>();
        try {
            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
            //因为查询出来的套餐的集合中封装了套餐的map,该map集合中的name的值和套餐名字集合所需要的数据一样的,所以需要
            //将该map集合中name对应的值添加到套餐名集合中,用于图例套餐名的展示
            if (setmealCount != null && setmealCount.size() > 0) {
                for (Map<String, Object> countmap : setmealCount) {
                    String name = (String) countmap.get("name");//获取到对应的套餐名称
                    setmealNames.add(name);
                }
            }
            map.put("setmealCount", setmealCount);
            map.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //运营数据统计查询
    @Reference
    private ReportService reportService;

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        //使用模拟数据测试使用什么样的java对象转为运营数据统计查询所需要的json格式.
        /*data: {
            reportData: {
                   reportDate: null,
                   todayNewMember: 0,
                   totalMember: 0,
                   thisWeekNewMember: 0,
                   thisMonthNewMember: 0,
                   todayOrderNumber: 0,
                   todayVisitsNumber: 0,
                   thisWeekOrderNumber: 0,
                   thisWeekVisitsNumber: 0,
                   thisMonthOrderNumber: 0,
                   thisMonthVisitsNumber: 0,
                   hotSetmeal: [
                       {name: '阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐', setmeal_count: 200, proportion: 0.222},
                       {name: '阳光爸妈升级肿瘤12项筛查体检套餐', setmeal_count: 200, proportion: 0.222}
                ]
            }*/
       /* Date date = new Date();
        String date1 = DateUtils.parseDate2String(date);
        Map<String, Object> map = new HashMap<>();
        map.put("reportDate", date1);
        map.put("todayNewMember", 100);
        map.put("totalMember", 1000);
        map.put("thisWeekNewMember", 300);
        map.put("thisMonthNewMember", 500);
        map.put("todayOrderNumber", 30);
        map.put("todayVisitsNumber", 20);
        map.put("thisWeekOrderNumber", 150);
        map.put("thisWeekVisitsNumber", 100);
        map.put("thisMonthOrderNumber", 300);
        map.put("thisMonthVisitsNumber", 200);
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐");
        map1.put("setmeal_count", 200);
        map1.put("proportion", 0.222);
        list.add(map1);
        map.put("hotSetmeal", list);*/
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");

            //动态获取模板的绝对路径
            String filePath = req.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //基于提供的Excel模板文件在内存中创建了Excel表格对象,来读取创建好的excel文件
            Workbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            Row row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map<String, Object> map1 : hotSetmeal) {
                String name = (String) map1.get("name");
                Long setmeal_count = (Long) map1.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map1.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//名称
                row.getCell(5).setCellValue(setmeal_count);//数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream outputStream = resp.getOutputStream();
            //设置消息头,表名文件的类型以及用什么方式打开该文件
            resp.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            resp.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

}
